package handlers

import (
	"net/http"
	"qcoder_reader/middleware"
	"qcoder_reader/models"
	"qcoder_reader/utils"

	"github.com/gin-gonic/gin"
	consulapi "github.com/hashicorp/consul/api"
)

// 登录处理
func Login(c *gin.Context) {
	var req models.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if middleware.CheckCredentials(req.Username, req.Password) {
		c.JSON(http.StatusOK, models.LoginResponse{
			Token:   "admin-token",
			Success: true,
			Message: "登录成功",
		})
	} else {
		c.JSON(http.StatusUnauthorized, models.LoginResponse{
			Success: false,
			Message: "用户名或密码错误",
		})
	}
}

// 获取所有服务名称列表
func GetServices(c *gin.Context) {
	services, err := utils.GetAllServices()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 转换为前端需要的格式
	var serviceList []models.ServiceInfo
	for name, tags := range services {
		serviceInfo := models.ServiceInfo{
			Name: name,
			Tags: tags,
		}
		serviceList = append(serviceList, serviceInfo)
	}

	c.JSON(http.StatusOK, serviceList)
}

// 获取指定服务的所有实例
func GetServiceInstances(c *gin.Context) {
	serviceName := c.Param("name")
	if serviceName == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "服务名称不能为空"})
		return
	}

	// 获取服务详细信息
	details, err := utils.GetServiceDetails(serviceName)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 转换为前端需要的格式
	var instanceList []models.ServiceInstance
	for _, detail := range details {
		instance := models.ServiceInstance{
			ServiceID:   detail.ServiceID,
			ServiceTags: detail.ServiceTags,
		}
		instanceList = append(instanceList, instance)
	}

	c.JSON(http.StatusOK, instanceList)
}

// 新增服务
func AddService(c *gin.Context) {
	var req models.ServiceRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 注册服务到Consul
	service := &consulapi.AgentServiceRegistration{
		ID:      req.ID,
		Name:    req.Name,
		Address: req.Address,
		Port:    req.Port,
		Tags:    req.Tags,
		Meta:    req.Meta,
	}

	// 如果有健康检查配置
	if req.Check != nil {
		service.Check = &consulapi.AgentServiceCheck{
			HTTP:     req.Check.HTTP,
			Interval: req.Check.Interval,
			Timeout:  req.Check.Timeout,
		}
	}

	err := utils.RegisterService(service)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "服务注册成功"})
}

// 删除服务
func DeleteService(c *gin.Context) {
	serviceID := c.Param("id")
	if serviceID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "服务ID不能为空"})
		return
	}

	err := utils.DeregisterService(serviceID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "服务删除成功"})
}
